from rest_framework import serializers

from sers.models import Publish, Author, Book


class BookSerializer(serializers.Serializer):
    title = serializers.CharField()
    price = serializers.IntegerField()
    pub_date = serializers.DateField(required=False)
    publish_id = serializers.IntegerField(write_only=True)
    publish_name = serializers.CharField(source="publish.name", read_only=True)
    publish_email = serializers.CharField(source="publish.email", read_only=True)

    def validate_title(self, value):
        if 'django' not in value.lower():
            raise serializers.ValidationError("图书不是关于Django的")

    def validate(self, data):
        bread = data.get("bread")
        bcomment = data.get("bcomment")
        print(f"阅读量：{bread}")
        # if bread < bcomment:
        #     raise serializers.ValidationError('阅读量小于评论量')
        return data


class BookSerializer2(serializers.Serializer):
    title = serializers.CharField(max_length=32)
    price = serializers.IntegerField(required=False)
    pub_date = serializers.DateField(required=False)

    publish = serializers.PrimaryKeyRelatedField(
        queryset=Publish.objects.all())  # queryset用于反序列化做校验
    authors = serializers.PrimaryKeyRelatedField(
        queryset=Author.objects.all(), many=True)

    def create(self, validated_data):
        print("validated_data:", validated_data)
        authors = validated_data.pop('authors')
        book = Book.objects.create(**validated_data)
        book.save()
        book.authors.set(authors)
        return book

    def update(self, instance, validated_data):
        print("validated_data:", validated_data)
        authors = validated_data.pop('authors')
        for key, value in validated_data.items():
            setattr(instance, key, value)
        instance.save()

        instance.authors.set(authors)
        return instance


class BookSerializer3(serializers.ModelSerializer):

    class Meta:
        model = Book
        # write_only_fields = ('id', 'publish_id', 'authors_id')
        # fields = ('title', 'price', 'bread', 'bcomment', 'pub_date')
        fields = "__all__"
        read_only_fields = ('id', 'bread', 'bcomment')
        extra_kwargs = {
            'bread': {'min_value': 0},
            'bcomment': {'min_value': 0},
        }
